import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';

class NetworkInterceptors extends InterceptorsWrapper {
  final Dio dio;

  final List _requestLists = [];

  NetworkInterceptors(this.dio);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
    final String item = XinDongNetworking.instance.generateRecordName(options);
    if (_requestLists.contains(item)) {
      return handler.reject(
        DioException(
          requestOptions: options,
          type: DioExceptionType.cancel,
          error: '重复请求，被拦截取消！',
        ),
      );
    } else {
      final String message = "\n========================================\n"
          "网络请求：${options.method}\n"
          "- Uri:\n${options.uri}\n"
          "- Header:\n${options.headers}\n"
          "- Parameters:\n${options.queryParameters}\n"
          "- Body:\n${options.data}"
          "\n========================================\n";
      mDebugPrint(message);
      _requestLists.add(item);
    }
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    String item = XinDongNetworking.instance.generateRecordName(response.requestOptions);
    _requestLists.remove(item);

    String message = "\n=================== start ===================\n"
        "请求结果：${(response.statusCode == 200 ? '🍏 success 🍏' : '🍎 failure 🍎')} statusCode = ${response.statusCode}\n"
        "- Uri:\n${response.requestOptions.uri}\n"
        "- Data:\n${response.data}"
        // "- Data:\n${json.encode(response.data)}"
        "\n=================== finish ==================\n";
    mDebugPrint(message);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    String item = XinDongNetworking.instance.generateRecordName(err.requestOptions);
    _requestLists.remove(item);
    // 转换错误
    OSError error = XinDongNetworking.instance.convertError(err);

    final String message = "\n=================== start ===================\n"
        "网络层报错：🍎 failure 🍎 statusCode = ${error.errorCode}, ${error.message}, "
        "${err.requestOptions.uri}"
        "\n=================== finish ==================\n";
    mDebugPrint(message);

    // 不提示清单
    final list = XinDongNetworking.instance.doNotToastList + XinDongNetworking.instance.doNotToastSuccessList;
    bool isExist = list.any((element) => element == err.requestOptions.uri.path);
    if (isExist == false && error.errorCode != XinDongServerStatus.interceptCancelled) {
      showToast(error.message);
    }
  }
}
